#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include "rbtree.h"
#include "master_slave.h"


// 初始化当前树的哨兵节点（每个树独有）
void init_nil_node(RBTree *tree)
{
    tree->NIL_NODE = (Node *)kvs_malloc(sizeof(Node));
    tree->NIL_NODE->color = BLACK;
    tree->NIL_NODE->left = tree->NIL_NODE;
    tree->NIL_NODE->right = tree->NIL_NODE;
    tree->NIL_NODE->parent = tree->NIL_NODE;
    tree->NIL_NODE->key = NULL;
    tree->NIL_NODE->value = NULL;
}

// 创建新节点（复制字符串键值，关联当前树的哨兵）
Node *create_rb_node(RBTree *tree, const char *key, const char *value)
{
    Node *node = (Node *)kvs_malloc(sizeof(Node));
    node->key = strdup(key);     // 复制键
    node->value = strdup(value); // 复制值
    node->color = RED;
    node->left = tree->NIL_NODE; // 绑定当前树的哨兵
    node->right = tree->NIL_NODE;
    node->parent = tree->NIL_NODE;
    return node;
}

// 初始化红黑树（初始化size为0，创建独有哨兵）
RBTree *rb_init()
{
    RBTree *tree = (RBTree *)kvs_malloc(sizeof(RBTree));
    init_nil_node(tree); // 初始化当前树的哨兵
    tree->root = tree->NIL_NODE;
    tree->size = 0; // 初始节点数为0

    // 新增：初始化互斥锁（递归锁，避免同一线程重复加锁死锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutexattr_t mutex_attr;
    pthread_mutexattr_init(&mutex_attr);
    pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(&tree->mutex_lock, &mutex_attr);
    pthread_mutexattr_destroy(&mutex_attr);
#endif

    // 新增：初始化读写锁
#if RB_TREE_RW_LOCK
    // pthread_rwlock_init(&tree->rw_lock, NULL); // 读写锁默认属性即可
    //  新增：设置读写锁为写者优先属性
    pthread_rwlockattr_t rw_attr;
    pthread_rwlockattr_init(&rw_attr);
// 设置写者优先（不同系统宏定义可能不同，Linux用PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP）
#ifdef PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP
    pthread_rwlockattr_setkind_np(&rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
#elif defined(PTHREAD_RWLOCK_PREFER_WRITER)
    pthread_rwlockattr_setkind(&rw_attr, PTHREAD_RWLOCK_PREFER_WRITER);
#endif
    // 用带属性的初始化替换默认初始化
    pthread_rwlock_init(&tree->rw_lock, &rw_attr);
    pthread_rwlockattr_destroy(&rw_attr); // 销毁属性结构体

#endif
    return tree;
}

// 左旋操作（使用当前树的哨兵节点）
void left_rotate(RBTree *tree, Node *x)
{
    Node *y = x->right;
    x->right = y->left;

    if (y->left != tree->NIL_NODE)
    {
        y->left->parent = x;
    }

    y->parent = x->parent;

    if (x->parent == tree->NIL_NODE)
    {
        tree->root = y;
    }
    else if (x == x->parent->left)
    {
        x->parent->left = y;
    }
    else
    {
        x->parent->right = y;
    }

    y->left = x;
    x->parent = y;
}

// 右旋操作（使用当前树的哨兵节点）
void right_rotate(RBTree *tree, Node *y)
{
    Node *x = y->left;
    y->left = x->right;

    if (x->right != tree->NIL_NODE)
    {
        x->right->parent = y;
    }

    x->parent = y->parent;

    if (y->parent == tree->NIL_NODE)
    {
        tree->root = x;
    }
    else if (y == y->parent->right)
    {
        y->parent->right = x;
    }
    else
    {
        y->parent->left = x;
    }

    x->right = y;
    y->parent = x;
}

// 插入后修复（使用当前树的哨兵节点）
void insert_fixup(RBTree *tree, Node *z)
{
    while (z->parent->color == RED)
    {
        if (z->parent == z->parent->parent->left)
        {
            Node *y = z->parent->parent->right;

            if (y->color == RED)
            {
                z->parent->color = BLACK;
                y->color = BLACK;
                z->parent->parent->color = RED;
                z = z->parent->parent;
            }
            else
            {
                if (z == z->parent->right)
                {
                    z = z->parent;
                    left_rotate(tree, z);
                }
                z->parent->color = BLACK;
                z->parent->parent->color = RED;
                right_rotate(tree, z->parent->parent);
            }
        }
        else
        {
            Node *y = z->parent->parent->left;

            if (y->color == RED)
            {
                z->parent->color = BLACK;
                y->color = BLACK;
                z->parent->parent->color = RED;
                z = z->parent->parent;
            }
            else
            {
                if (z == z->parent->left)
                {
                    z = z->parent;
                    right_rotate(tree, z);
                }
                z->parent->color = BLACK;
                z->parent->parent->color = RED;
                left_rotate(tree, z->parent->parent);
            }
        }
    }
    tree->root->color = BLACK;
}

// 插入节点（新增size更新逻辑，使用当前树的哨兵）
int rb_insert(RBTree *tree, const char *key, const char *value)
{
    if (!tree || !key || !value) return -1;

    // 新增：加锁（写操作：互斥锁/写锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_wrlock(&tree->rw_lock);
#endif

    Node *z = create_rb_node(tree, key, value); // 传递树实例
    Node *y = tree->NIL_NODE;
    Node *x = tree->root;

    // 查找插入位置
    while (x != tree->NIL_NODE)
    {
        y = x;
        int cmp = strcmp(z->key, x->key);
        if (cmp < 0)
        {
            x = x->left;
        }
        else if (cmp > 0)
        {
            x = x->right;
        }
        else
        {
            // 键已存在，更新值（不改变节点数）
            // kvs_free(x->value);
            // x->value = strdup(value);
            kvs_free(z->key);
            kvs_free(z->value);
            kvs_free(z);

            // 新增：解锁
#if RB_TREE_MUTEX_LOCK
            pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
            pthread_rwlock_unlock(&tree->rw_lock);
#endif
            return 1;
        }
    }

    z->parent = y;
    if (y == tree->NIL_NODE)
    {
        tree->root = z; // 树为空，新节点为根
    }
    else if (strcmp(z->key, y->key) < 0)
    {
        y->left = z;
    }
    else
    {
        y->right = z;
    }

    // 新节点插入成功，节点数+1
    tree->size++;

    // 根节点处理
    if (z->parent == tree->NIL_NODE)
    {
        z->color = BLACK;
        // 新增：解锁
#if RB_TREE_MUTEX_LOCK
        pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
        pthread_rwlock_unlock(&tree->rw_lock);
#endif
        return 0;
    }
    if (z->parent->parent == tree->NIL_NODE)
    {
        // 新增：解锁
#if RB_TREE_MUTEX_LOCK
        pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
        pthread_rwlock_unlock(&tree->rw_lock);
#endif
        return 0;
    }

    insert_fixup(tree, z);

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
    return 0;
}

// 查找节点（使用当前树的哨兵节点）
Node *rb_search(RBTree *tree, const char *key)
{
    // 新增：加锁（读操作：互斥锁/读锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_rdlock(&tree->rw_lock);
#endif

    Node *x = tree->root;
    while (x != tree->NIL_NODE)
    {
        int cmp = strcmp(key, x->key);
        if (cmp == 0)
        {
            // 新增：解锁
#if RB_TREE_MUTEX_LOCK
            pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
            pthread_rwlock_unlock(&tree->rw_lock);
#endif
            return x;
        }
        else if (cmp < 0)
        {
            x = x->left;
        }
        else
        {
            x = x->right;
        }
    }

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
    return NULL;
}

Node *unlock_rb_search(RBTree *tree, const char *key)
{
    Node *x = tree->root;
    while (x != tree->NIL_NODE)
    {
        int cmp = strcmp(key, x->key);
        if (cmp == 0)
        {
            return x;
        }
        else if (cmp < 0)
        {
            x = x->left;
        }
        else
        {
            x = x->right;
        }
    }
    return NULL;
}

// 修改节点值（不变）
int rb_update(RBTree *tree, const char *key, const char *new_value)
{
    if (!tree || !key || !new_value) return -1;

    // 新增：加锁（写操作：互斥锁/写锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_wrlock(&tree->rw_lock);
#endif

    Node *node = unlock_rb_search(tree, key);
    if (node)
    {
        kvs_free(node->value);
        node->value = strdup(new_value);

        // 新增：解锁
#if RB_TREE_MUTEX_LOCK
        pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
        pthread_rwlock_unlock(&tree->rw_lock);
#endif
        return 0;
    }

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
    return -1;
}

// 获取子树最小值节点（使用当前树的哨兵节点）
Node *rb_minimum(RBTree *tree, Node *x)
{
    while (x->left != tree->NIL_NODE)
    {
        x = x->left;
    }
    return x;
}

// 替换节点（使用当前树的哨兵节点）
void rb_transplant(RBTree *tree, Node *u, Node *v)
{
    if (u->parent == tree->NIL_NODE)
    {
        tree->root = v;
    }
    else if (u == u->parent->left)
    {
        u->parent->left = v;
    }
    else
    {
        u->parent->right = v;
    }
    v->parent = u->parent;
}

// 删除后修复（使用当前树的哨兵节点）
void delete_fixup(RBTree *tree, Node *x)
{
    while (x != tree->root && x->color == BLACK)
    {
        if (x == x->parent->left)
        {
            Node *s = x->parent->right;

            if (s->color == RED)
            {
                s->color = BLACK;
                x->parent->color = RED;
                left_rotate(tree, x->parent);
                s = x->parent->right;
            }

            if (s->left->color == BLACK && s->right->color == BLACK)
            {
                s->color = RED;
                x = x->parent;
            }
            else
            {
                if (s->right->color == BLACK)
                {
                    s->left->color = BLACK;
                    s->color = RED;
                    right_rotate(tree, s);
                    s = x->parent->right;
                }
                s->color = x->parent->color;
                x->parent->color = BLACK;
                s->right->color = BLACK;
                left_rotate(tree, x->parent);
                x = tree->root;
            }
        }
        else
        {
            Node *s = x->parent->left;

            if (s->color == RED)
            {
                s->color = BLACK;
                x->parent->color = RED;
                right_rotate(tree, x->parent);
                s = x->parent->left;
            }

            if (s->right->color == BLACK && s->left->color == BLACK)
            {
                s->color = RED;
                x = x->parent;
            }
            else
            {
                if (s->left->color == BLACK)
                {
                    s->right->color = BLACK;
                    s->color = RED;
                    left_rotate(tree, s);
                    s = x->parent->left;
                }
                s->color = x->parent->color;
                x->parent->color = BLACK;
                s->left->color = BLACK;
                right_rotate(tree, x->parent);
                x = tree->root;
            }
        }
    }
    x->color = BLACK;
}

// 删除节点（新增size更新逻辑，使用当前树的哨兵）
int rb_delete(RBTree *tree, const char *key)
{
    if (!tree || !key) return -1;
    // 新增：加锁（写操作：互斥锁/写锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_wrlock(&tree->rw_lock);
#endif

    Node *z = unlock_rb_search(tree, key); // 内部已加解锁（递归锁兼容）
    if (!z)
    {
        // 新增：解锁
#if RB_TREE_MUTEX_LOCK
        pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
        pthread_rwlock_unlock(&tree->rw_lock);
#endif
        return -1; // 节点不存在，不改变节点数
    }

    Node *y = z;
    Node *x;
    Color y_original_color = y->color;

    if (z->left == tree->NIL_NODE)
    {
        x = z->right;
        rb_transplant(tree, z, z->right);
    }
    else if (z->right == tree->NIL_NODE)
    {
        x = z->left;
        rb_transplant(tree, z, z->left);
    }
    else
    {
        y = rb_minimum(tree, z->right);
        y_original_color = y->color;
        x = y->right;

        if (y->parent == z)
        {
            x->parent = y;
        }
        else
        {
            rb_transplant(tree, y, y->right);
            y->right = z->right;
            y->right->parent = y;
        }

        rb_transplant(tree, z, y);
        y->left = z->left;
        y->left->parent = y;
        y->color = z->color;
    }

    // 释放节点内存，节点数-1
    kvs_free(z->key);
    kvs_free(z->value);
    kvs_free(z);
    tree->size--; // 成功删除，节点数减少

    if (y_original_color == BLACK)
    {
        delete_fixup(tree, x);
    }

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
    return 0;
}

// 新增：获取节点总数
int rb_get_size(RBTree *tree)
{
    // 新增：加锁（读操作：互斥锁/读锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_rdlock(&tree->rw_lock);
#endif

    int size = tree->size;

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
    return size;
}

// 中序遍历（修改：使用当前树的哨兵节点）
void inorder_traversal(RBTree *tree, Node *node)
{
    // 新增：加锁（读操作：互斥锁/读锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_rdlock(&tree->rw_lock);
#endif

    if (node != tree->NIL_NODE)
    {
        inorder_traversal(tree, node->left);
        printf("Key: %s, Value: %s, Color: %s\n",
               node->key, node->value,
               node->color == RED ? "RED" : "BLACK");
        inorder_traversal(tree, node->right);
    }

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif
}

// 销毁节点（使用当前树的哨兵节点）
void rb_destroy_node(RBTree *tree, Node *node)
{
    if (node != tree->NIL_NODE)
    {
        rb_destroy_node(tree, node->left);
        rb_destroy_node(tree, node->right);
        kvs_free(node->key);
        kvs_free(node->value);
        kvs_free(node);
    }
}

// 删除所有节点，保留红黑树
int rb_clear(RBTree *tree)
{
    if (!tree)
        return -1; // 入参校验

    // 新增：加锁（写操作：互斥锁/写锁）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_wrlock(&tree->rw_lock);
#endif

    // 递归销毁所有数据节点（跳过哨兵）
    rb_destroy_node(tree, tree->root);

    // 重置红黑树状态
    tree->root = tree->NIL_NODE;
    tree->size = 0;

    // 新增：解锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
#endif

    return 0;
}

// 销毁红黑树（释放独有哨兵节点）
void rb_destroy(RBTree *tree)
{
    if (!tree)
        return;

    // 新增：加锁（确保销毁时无其他线程操作）
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_lock(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_wrlock(&tree->rw_lock);
#endif

    rb_destroy_node(tree, tree->root);
    kvs_free(tree->NIL_NODE); // 释放当前树的哨兵

    // 新增：销毁锁
#if RB_TREE_MUTEX_LOCK
    pthread_mutex_unlock(&tree->mutex_lock);
    pthread_mutex_destroy(&tree->mutex_lock);
#elif RB_TREE_RW_LOCK
    pthread_rwlock_unlock(&tree->rw_lock);
    pthread_rwlock_destroy(&tree->rw_lock);
#endif

    kvs_free(tree);
}


// ======================== 全量持久化 ============================
// 辅助函数：遍历红黑树并写入文件（中序遍历）
static int rb_traverse_persist(RBTree *tree, Node *node, int fd)
{
    if (node == tree->NIL_NODE)
        return 0;

    // 递归遍历左子树
    if (rb_traverse_persist(tree, node->left, fd) != 0)
        return -1;

    // 写入当前节点：键长(4字节) + 值长(4字节) + 键 + 值
    int key_len = strlen(node->key);
    int val_len = strlen(node->value);

#if 1 // MASTER_SLAVE 为了方便各种模式都能使用正常同一个文件，这里统一存储/读取方式
    // 关键：转换为网络字节序（大端）
    uint32_t net_key_len = htonl(key_len);
    uint32_t net_val_len = htonl(val_len);

    struct iovec iov[4];
    iov[0].iov_base = &net_key_len; // 用转换后的网络字节序
    iov[0].iov_len = 4;
    iov[1].iov_base = &net_val_len; // 用转换后的网络字节序
    iov[1].iov_len = 4;
    iov[2].iov_base = node->key;
    iov[2].iov_len = key_len;
    iov[3].iov_base = node->value;
    iov[3].iov_len = val_len;
#else
    struct iovec iov[4];
    iov[0].iov_base = &key_len;
    iov[0].iov_len = 4;
    iov[1].iov_base = &val_len;
    iov[1].iov_len = 4;
    iov[2].iov_base = node->key;
    iov[2].iov_len = key_len;
    iov[3].iov_base = node->value;
    iov[3].iov_len = val_len;
#endif
    // 批量写入，确保节点数据原子性（要么全写，要么全失败）
    ssize_t total = writev(fd, iov, 4);
    if (total != 4 + 4 + key_len + val_len)
    {
        perror("traverse persist writev failed");
        return -1;
    }

    // 递归遍历右子树
    if (rb_traverse_persist(tree, node->right, fd) != 0)
        return -1;

    return 0;
}

// 全量持久化实现
int rb_full_store(RBTree *tree, const char *full_filename)
{
    if (!tree || !full_filename)
        return -1;

    // 打开文件：创建+覆盖写入（O_TRUNC），权限0644
    int fd = open(full_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
    {
        perror("full persist open failed");
        return -1;
    }

    // 遍历树并写入数据
    int ret = rb_traverse_persist(tree, tree->root, fd);

    // 强制刷盘，确保数据落盘
    fsync(fd);
    close(fd);

    return ret;
}

// 全量持久化（保留历史备份）
int rb_full_store_with_backup(RBTree *tree, const char *full_filename)
{
    if (!tree || !full_filename)
        return -1;

    // 1. 若旧文件存在，重命名为历史备份（如 filename.202410251430）
    struct stat st;
    if (stat(full_filename, &st) == 0)
    { // 检查文件是否存在
        char backup_filename[256];
        time_t now = time(NULL);
        struct tm *tm = localtime(&now);
        // 格式化时间戳：filename.YYYYMMDDHHMM
        snprintf(backup_filename, sizeof(backup_filename),
                 "%s.%04d%02d%02d%02d%02d",
                 full_filename, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
                 tm->tm_hour, tm->tm_min);
        rename(full_filename, backup_filename); // 重命名旧文件为备份
    }

    // 2. 打开新文件（O_TRUNC 清空，实际是创建新文件）
    int fd = open(full_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
    {
        perror("full persist open failed");
        return -1;
    }

    // 3. 写入新的全量数据（后续逻辑与之前一致）
    int ret = rb_traverse_persist(tree, tree->root, fd);
    fsync(fd);
    close(fd);

    return ret;
}

// 全量恢复实现

int rb_full_restore(const char *full_filename, RBTree* tree)
{
    if (!full_filename || !tree)
        return -1;

    // 打开文件：只读模式,fd为阻塞
    int fd = open(full_filename, O_RDONLY);
    if (fd == -1)
    {
        perror("full restore open failed");
        return -1;
    }

#if 1 // MASTER_SLAVE 为了方便各种模式都能使用正常同一个文件，这里统一存储/读取方式
    uint32_t net_key_len, net_val_len; // 网络字节序存储
#endif

    int key_len, val_len;
    char *key_buf = NULL;  // 声明为NULL，后续动态分配
    char *val_buf = NULL;  // 声明为NULL，后续动态分配

    long int read_key_value_num = 0;
    int is_eof = 0; // 新增：标记是否为EOF正常结束
    // 循环读取每个节点的数据
    while (1)
    {

#if 1 // MASTER_SLAVE 为了方便各种模式都能使用正常同一个文件，这里统一存储/读取方式
        // 读键长（网络字节序）
        ssize_t n = read(fd, &net_key_len, 4);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != 4)
            break;
        key_len = ntohl(net_key_len); // 关键：转换为主机字节序

        // 读值长（网络字节序）
        n = read(fd, &net_val_len, 4);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != 4)
            break;
        val_len = ntohl(net_val_len); // 关键：转换为主机字节序
#else
        // 读键长
        ssize_t n = read(fd, &key_len, 4);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != 4)
            break;
        // 读值长
        n = read(fd, &val_len, 4);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != 4)
            break;
#endif
        // 校验长度（避免无效长度）
        if (key_len <= 0 || val_len <= 0)
        {
            fprintf(stderr, "invalid key/val length in persist file\n");
            break;
        }

        // 动态分配键缓冲区（+1用于存储字符串结束符）
        key_buf = kvs_malloc(key_len + 1);
        if (!key_buf)
        {
            perror("kvs_malloc key_buf failed");
            break;
        }

        // 动态分配值缓冲区（+1用于存储字符串结束符）
        val_buf = kvs_malloc(val_len + 1);
        if (!val_buf)
        {
            perror("kvs_malloc val_buf failed");
            kvs_free(key_buf);  // 释放已分配的键缓冲区
            key_buf = NULL;
            break;
        }

        // 读键
        n = read(fd, key_buf, key_len);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != key_len)
            break;
        key_buf[key_len] = '\0'; // 手动添加字符串结束符

        // 读值
        n = read(fd, val_buf, val_len);
        if (n == 0)
        {
            is_eof = 1;
            break;
        } // 新增：判断EOF
        if (n != val_len)
            break;
        val_buf[val_len] = '\0';

        // 插入红黑树（自动维护平衡结构）
        rb_insert(tree, key_buf, val_buf);
        read_key_value_num++;

        // 释放当前节点的缓冲区（循环复用）
        kvs_free(key_buf);
        kvs_free(val_buf);
        key_buf = NULL;
        val_buf = NULL;
    }

    LOG("成功读取了%ld个节点\n", read_key_value_num);
    // 检查是否正常读取完毕（仅当非EOF且errno非0非EINTR时报错）
    if (!is_eof && errno != 0 && errno != EINTR)
    {
        perror("restore read failed");
        rb_destroy(tree);
        tree = NULL;
    }

    // 释放可能残留的缓冲区（若循环提前退出）
    if (key_buf) kvs_free(key_buf);
    if (val_buf) kvs_free(val_buf);
    close(fd);

    return 0;
}
